<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick, computed } from 'vue'
import * as echarts from 'echarts';

const props = defineProps({
  // 图表配置
  option: {
    type: Object,
    default: () => {
      return {}
    }
  },
  // 是否自动适应窗口大小
  isResize: {
    type: Boolean,
    default: false
  },
  // 适应窗口大小延迟时间,小于或等于
  // 0则不启用延时
  resizeDelayed: {
    type: Number,
    default: 0
  },
  // 深度监听option
  deepOption: {
    type: Boolean,
    default: false
  },
  // 深色模式
  dark: {
    type: Boolean,
    default: false
  },
})
const emit = defineEmits(['click'])
const chartRef = ref()

let chartInstance;
let timeouter;

// 监听窗口大小变化事件
function onChartResize() {
  if (!chartInstance) return
  if (props.resizeDelayed <= 0) {
    chartInstance.resize();
  } else {
    timeouter && clearTimeout(timeouter);
    timeouter = setTimeout(function () {
      chartInstance.resize();
    }, props.resizeDelayed);
  }
}
// 绘制图表
function drawChart() {
  if (!chartInstance) return
  chartInstance.setOption(props.option || {}, true);
}
// 初始化图表实例
function initChart() {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value, props.dark ? 'dark' : '');
  // 绑定点击事件
  chartInstance.on('click', function (params) {
    emit('click', params, params.name)
  });
  // 监听窗口大小变化事件
  if (props.isResize) {
    window.addEventListener('resize', onChartResize);
  }

  drawChart()
}

defineExpose({
  dispose: () => {
    chartInstance && chartInstance.dispose()
    window.removeEventListener("resize", onChartResize);
  },
  resize: () => {
    chartInstance && chartInstance.resize()
  },
})


onMounted(() => {
  nextTick(() => initChart())
})

// 页面卸载时清除resize监听事件
onUnmounted(() => {
  chartInstance && chartInstance.dispose()
  window.removeEventListener("resize", onChartResize);
})

// 监听配置变化重新绘制图表
watch(() => props.option, () => {
  drawChart()
}, { deep: props.deepOption })
</script>

<template>
  <div ref="chartRef"></div>
</template>
